﻿(function () {
    $.connection.hub.url = "http://localhost:8080/signalr";
    var chat_main = $.connection.mainHub;
    var chatHub = $.connection.chatHub;
    Main = {};
    Main.Instance = {
        Init: function () {
            this.CreateConnected();
            this.NoticeClient();
            $(document).on('click', '.status', this.ShowStatus);
            $(document).on('click', '#showPack', this.ShowBackPack);
            $(document).on('click', '#raid', this.ShowRaidList);
            $(document).on('click', '.item', this.RaidClick);
            $(document).on('click', '#existRaid', this.CloseLayer);
            $(document).on('click', 'button[name="fight"]', this.RaidFight);
            $(document).on('click', '#closeRaidList', this.CloseRaidList);
            $(document).on('click', '.chatbtn', this.ShowChatDiv);
            $(document).on('click', '.noneChat', this.ChoseChat);
            $(document).on('click', '.author_name', this.ClickChatRole);
            $(document).on('click', '#sendMsg', this.SendMsg);
            $(document).on('click', '#cancelChat', this.CloseChatDiv);
            $(document).on('click', '.author_name', this.ShowOption);
            $(document).on('click', '.cancelShowOption', this.CancelShowOption);
            $(document).on('click', '.showPrivateChatBox', this.ShowPrivateChatBox);
            $(document).on('click', '.seeRoleDetail', this.SeeRoleDetail);
        },
        SeeRoleDetail: function () {
            var heroId = $(this).attr("heroId");
            var un = $(this).attr("un");
            if (heroId == "" || un == "")
                return false;
            bDialog.open({
                backdrop: 'true',
                title: '角色信息',
                width: '100%',
                height: '90%',
                customClass: 'simple',
                url: '/Home/ShowOtherRoleStatus?token=' + ToolManager.Common.Token()+'&heroId='+heroId+'&un='+un
            });
        },
        ShowPrivateChatBox: function () {
            var toConnectionId = $(this).attr("connectionId");
            var toRoleName = $(this).attr("toRoleName");
            $(".showOption").remove();
            ToolManager.Layer.SelfSet('<p>请输入要发送的消息:</p><input id="private_msg" type="text" /><p><span id="errmsg" style="color:red"></span></p>', '发送', '取消', function (index) {
                var msg = $("#private_msg").val().trim();
                if (msg == "") {
                    $("#errmsg").text("消息不能为空");
                    return false;
                }

                var sendModel = {};
                sendModel.SendConnectionId = UserBase.SignalrInfo.ConnectedId;
                sendModel.SendMsg = msg;
                sendModel.ChatType = 2;
                sendModel.ToConnectionId = toConnectionId;
                sendModel.ToRoleName = toRoleName;
                chatHub.server.sendMsg(sendModel);
                layer.close(index);
            });
        },
        CancelShowOption: function () {
            $(".showOption").each(function () {
                $(this).remove();
            })
        },
        ShowOption: function () {
            //判断是否是自己，如果是，不显示
            if ($(this).attr("un") == "" || $(this).attr("un") == undefined)
                return false;
            $(".showOption").each(function () {
                $(this).remove();
            })
            var resHtml = [];
            resHtml.push('<div class="showOption" style="width: 56px;height: 74px;background-color:#D44;position:  absolute;z-index:  999;left:  4%;margin-top: -15px;">')
            resHtml.push('<ul style="list-style:none;text-align:  center;line-height: 25px;">');
            resHtml.push('<li><a heroId="'+$(this).attr("heroId")+'" un="' + $(this).attr("un") + '" href="javascript:void(0);" class="seeRoleDetail">查看</a></li>');
            resHtml.push('<li><a toRoleName="' + $(this).attr("SendRoleName") + '" connectionId="' + $(this).attr("ToConnectionId") + '" href="javascript:void(0);" class="showPrivateChatBox">私聊</a></li>');
            resHtml.push('<li><a  href="javascript:void(0);" class="cancelShowOption">取消</a></li>');
            resHtml.push('</ul>');
            resHtml.push('</div>');
            $(this).after(resHtml.join(''));
        },
        //点击聊天角色名称
        ClickChatRole: function () {
            //$("#sendMsg").html('@' + $(this).attr("SendRoleName") + ':');
            //$("#privateChatInfo").attr("toConnectionId", $(this).attr("ToConnectionId"));
        },
        CloseChatDiv: function () {
            $("#chatDiv").hide();
        },
        ShowChatDiv: function () {
            $("#chatDiv").show();
            $(".messageNum").html(0).hide();
        },
        ChoseChat: function () {
            var chatType = $(this).attr("chatType");
            $('.noneChat').each(function () {
                $(this).removeClass("choseChat");
                $(this).attr("isChose", "0");
            })
            $(this).addClass("choseChat");
            $("#msgNum_" + chatType + "").html(0).hide();
            $("#chatContent_" + chatType + "").show().siblings().hide();

            $(this).attr("isChose", "1");
        },
        HeroId: ToolManager.Common.UrlParms("heroId"),
        RaidClick: function () {
            $(this).next().slideToggle(100);
            $('p').not($(this).next()).slideUp('fast');
        },
        CloseRaidList: function () {
            layer.closeAll();
        },
        CloseLayer: function () {
            ToolManager.Layer.SelfSet("如果返回此次战斗将作废,您确定返回吗?", '确定', '取消', function () {
                layer.closeAll();
            })

        },
        RaidFight: function () {
            var raidId = $(this).attr("raidId");
            var loadingIndex = ToolManager.Layer.Loding("场景加载中.....");
            debugger;
            webExpress.utility.ajax.request("/Raid/LoadRaidData?token=" + ToolManager.Common.Token(), { "raidId": raidId, "heroId": UserBase.Status.HeroId }, function (data) {
                if (data.IsSuccess) {
                    if (data.Data.RoleSkills.length <= 0 || data.Data.Monsters.length <= 0) {
                        ToolManager.Layer.ErrorTimeMsg("数据加载失败", 2);
                        layer.closeAll("loading");
                        return false;
                    }
                    //副本场景加载
                    var raidHtml = RaidModel.Bussiness.CreateRaidHtml(data);
                    
                    //当前副本的怪信息
                    MonsterModel.CurrentFight = data.Data.Monsters;
                    var raidScreen = layer.open({
                        type: 1,
                        content: raidHtml,
                        anim: 'up',
                        style: 'position:fixed; left:0; top:0; width:100%; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;overflow:auto'
                    });
                    _fightStatus = 0;
                    _intervalLock = false;
                    var raidItem = RaidModel.Bussiness.GetRaidById(raidId);
                    //当前副本注册怪物AI
                    RaidFight.Instance.InitMonsterAiAttack();
                    $(".layui-m-layerchild").css("background-image", "url('" + raidItem.ImgPath + "1')");//副本背景
                    //角色被动效果动画
                    SkillModel.Bussiness.SetPassiveCss(data.Data.RoleSkills);
                    ToolManager.Layer.Close(loadingIndex);

                } else {
                    ToolManager.Layer.ErrorTimeMsg(data.Message, 2);
                }
            });
        },

        //副本信息
        ShowRaidList: function () {
            var htmlArr = RaidModel.Bussiness.ShowRaidList();
            var pageii = layer.open({
                type: 1,
                content: htmlArr,
                anim: 'up',
                style: 'position:fixed; left:0; top:0; width:100%; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;overflow:auto'
            });
        },
        //状态信息
        ShowStatus: function () {
            //ToolManager.UI.OpenTitle("状态");
            bDialog.open({
                backdrop: 'true',
                title: '角色信息',
                width: '100%',
                height: '90%',
                customClass: 'simple',
                url: '/Home/Status?token=' + ToolManager.Common.Token()
            });
        },
        //背包
        ShowBackPack: function () {
            bDialog.open({
                backdrop: 'true',
                title: '背包信息',
                width: '100%',
                height: '90%',
                customClass: 'simple',
                url: '/Home/BackPack?token=' + ToolManager.Common.Token()
            });
        },
        CreateConnected: function () {
            var un = $("#un").val();
            var heroId = this.HeroId;
            if (un == "" || heroId == "") {
                ToolManager.Common.JumpChose("网络连接异常,请从新进入");
            }
            $.connection.hub.start().done(function () {
                chat_main.server.createConnected(un, heroId);
                ToolManager.Common.AddMsg("正在连接服务器......");
            });
        },
        //发送消息
        SendMsg: function () {//1，消息发送者，2，消息接受者
            var chatObj = $(".noneChat[isChose=1]");
            var sendModel = {};
            var sendMsg = $("#sendInputMsg").val();
            if (sendMsg == "") {
                return false;
            }
            sendModel.SendConnectionId = UserBase.SignalrInfo.ConnectedId;
            if (chatObj.attr("chatType") == 2)//私聊不在这里发送
                return false;
            switch (chatObj.attr("chatType")) {
                case "1":
                    //普通
                    sendModel.ChatType = 1;
                    sendModel.SendMsg = sendMsg;
                    break;
                    //case "2":
                    //    //私聊
                    //    //输入框没有冒号或者被发送人连接ID不存在，不允许发送
                    //    var toConnectionId = $("#privateChatInfo").attr("toConnectionId");
                    //    if (toConnectionId == "" || sendMsg.indexOf(":") < 0 || sendMsg.split(':')[1] == "") {
                    //        return false;
                    //    }
                    //    sendModel.SendMsg = sendMsg.split(':')[1];
                    //    sendModel.ChatType = 2;
                    //    sendModel.ToConnectionId = toConnectionId;
                    //    break;
            }

            chatHub.server.sendMsg(sendModel);
            $("#sendInputMsg").val("");

        },
        //服务器通信给客户端
        NoticeClient: function () {
            //连接通知
            chat_main.client.connectedReceive = function (rtn) {
                if (rtn.IsSuccess) {
                    UserBase.SignalrInfo.UserName = rtn.Data.UserName;
                    UserBase.SignalrInfo.ConnectedId = rtn.Data.ConnectedId;
                    //加载当前用户属性面板(基本+装备),装备列表
                    SyncLoadUserInfoModelAndEqs();
                    //异步加载用户背包信息
                    SyncLoadUserBackPack();
                    //异步加载状态列表技能信息
                    SyncLoadSkillList();
                    //异步加载副本列表信息
                    SyncLoadRaidList();

                    ToolManager.Common.AddMsg("服务器连接成功...");
                } else {
                    ToolManager.Common.JumpChose("服务器连接失败");
                }
            };

            //公共通知
            chatHub.client.NoticeMsg = function (msg) {
                ToolManager.Layer.ErrorTimeMsg(msg, 2);
            }
            //所有人频道消息通知
            chatHub.client.SendMsgReceiveForAll = function (rtn) {
                if (rtn.IsSuccess) {
                    $("#chatContent_1").append(CreateMsg(rtn.Data));
                    //提示
                    if ($("#chatDiv").css("display") == "none") {
                        var outNum = parseInt($(".messageNum").html()) + 1;
                        $(".messageNum").html(outNum).show();
                    } else {
                        //当前选择是否在普通频道
                        var chatObj = $(".noneChat[isChose=1]");

                        if (chatObj.attr("chatType") != "1") {
                            var putongNum = parseInt($("#msgNum_1").html()) + 1;
                            $("#msgNum_1").html(putongNum).show();
                        }
                    }
                    $('.chat-scroll-content').animate({ scrollTop: $("#chatContent_1").innerHeight() }, 800);
                }
            }
            //私聊频道通知
            chatHub.client.SnedMsgReceiveForPrivate = function (rtn) {
                if (rtn.IsSuccess) {
                    $("#chatContent_2").append(CreateMsg(rtn.Data));
                    //提示
                    if ($("#chatDiv").css("display") == "none") {
                        var outNum = parseInt($(".messageNum").html()) + 1;
                        $(".messageNum").html(outNum).show();
                    } else {
                        //当前选择是否在普通频道
                        var chatObj = $(".noneChat[isChose=1]");
                        if (chatObj.attr("chatType") != "2") {
                            //如果是自己在其他频道对别人说的私聊，就不用提示了
                            if (rtn.Data.SendConnectionId != UserBase.SignalrInfo.ConnectedId) {
                                var siliaoNum = parseInt($("#msgNum_2").html()) + 1;
                                $("#msgNum_2").html(siliaoNum).show();
                            }
                        }
                    }
                    $('.chat-scroll-content').animate({ scrollTop: $("#chatContent_2").innerHeight() }, 800);
                }
            }

            CreateMsg = function (data) {
                var rel = [];
                rel.push('<div class="clearfix">');
                rel.push('<div class="chatMessage others">');
                rel.push('<div class="chatContent">');
                if (data.SendConnectionId == UserBase.SignalrInfo.ConnectedId) {
                    if (data.ChatType == 2) {
                        //私聊
                        rel.push('<p class="author_name">你对' + data.ToRoleName + '说</p>')
                    } else {
                        rel.push('<p class="author_name">你</p>')
                    }


                } else {
                    rel.push('<p heroId="'+data.HeroId+'" un="' + data.Un + '" SendRoleName="' + data.SendRoleName + '" ToConnectionId="' + data.SendConnectionId + '" class="author_name" style="color:' + ToolManager.Common.GetColorForLevel(data.GameLevel) + '">' + data.SendRoleName + '-' + data.SendRoleLevelTitle + '</p>')
                }

                rel.push('<div class="bubble  bubble_default chatleft">');
                rel.push('<div class="bubble_cont">');
                rel.push('<div class="plain">');
                if (data.ChatType == 2) {
                    rel.push(' <pre style="color:orangered">' + data.SendMsg + '</pre>');
                } else {
                    rel.push(' <pre>' + data.SendMsg + '</pre>');
                }
                rel.push(' </div>');
                rel.push(' </div>');
                rel.push(' </div>');
                rel.push(' </div>');
                rel.push(' </div>');
                rel.push(' </div>');
                return rel.join('');
            }

            SyncLoadUserBackPack = function () {
                UserBase.Common.SyncLoadUserBackPack();
            };
            SyncLoadUserInfoModelAndEqs = function () {
                UserBase.Common.SyncLoadUserInfoModelAndEqs();
            };
            SyncLoadSkillList = function () {
                UserBase.Common.SyncLoadSkillList();
            };
            SyncLoadRaidList = function () {
                webExpress.utility.ajax.request("/Raid/GetRaidList?token=" + ToolManager.Common.Token(), null, function (data) {
                    if (data.IsSuccess) {
                        RaidModel.RaidList = data.Data;
                    } else {
                        ToolManager.Common.JumpChose("数据加载失败,请从新进入");

                    }
                });
            }
        },


    };
})();
//下面注释的是列表的样式留着用
//htmlArr.push('<button style="background-color:#a53f3f" class="layui-btn layui-btn-warm layui-btn-radius">返回</button>');
//htmlArr.push('<div class="accordion">');
//for (var i = 0; i < RaidModel.RaidList.length; i++) {
//    htmlArr.push('<div class="item">');
//    htmlArr.push('<h3>' + RaidModel.RaidList[i].RaidName + '</h3>');
//    htmlArr.push('</div>');
//    htmlArr.push('<p>' + RaidModel.RaidList[i].Introduce + '</br><font color="#FFD700">冒险等级:' + RaidModel.RaidList[i].NeedLevel + '</font></p>');
//    htmlArr.push('<p> <button class="layui-btn layui-btn-normal layui-btn-radius">前往冒险</button></p>');
//}
//htmlArr.push('</div');